
import subprocess
from common_tool import common_DeleteAllCache, common_DownloadPath, common_ParseUrl, common_GetCommonCacheMission
from deal_m3u8_file import DealM3U8File
from download_m3u8 import Download_mission
from yaml_tool import YamlTool
import threading


def deal_m3u8file(host: str, path: str) -> bool:
    a_m3u8 = DealM3U8File(host=host, path=path)
    return a_m3u8.startMission()


def down_load_all_files(mission_count: int) -> bool:
    dm_missions: list[threading.Thread] = []
    for i in range(mission_count):
        dm = Download_mission(
            thread_name=f'线程_{str(i).zfill(3)}')
        dm_missions.append(dm)
        dm.start()

    for dm in dm_missions:
        dm.join()

    return True


def ffmpeg_mission(save_path: str, path: str) -> bool:
    common_cache_mission = common_GetCommonCacheMission()
    # 构建 ffmpeg 命令
    # ffmpeg -i xxx.m3u8 -vcodec copy -acodec copy xxx.mp4
    command = ['ffmpeg',
               '-allowed_extensions', 'ALL',
               '-protocol_whitelist', "file,http,crypto,tcp,https",
               '-i', common_cache_mission['m3u8_path'],
               '-c', 'copy',
               save_path]

    try:
        print(f'执行拼接命令')
        # 执行命令
        subprocess.run(command, check=True)
        print(f"文件拼接成功,地址是: {save_path}")
        # 删除其他的内容
        common_DeleteAllCache(path=path)
    except subprocess.CalledProcessError as e:
        print(f"文件拼接失败: {e}")


if __name__ == '__main__':

    config = YamlTool.readData('./config.yaml')
    url = config['下载地址']
    save_name = config['保存名字']
    mission_count = config['线程个数']

    """
        解析URL
    """
    host, path = common_ParseUrl(url=url)
    res = deal_m3u8file(host=host, path=path)

    if res == True:
        down_load_res = down_load_all_files(mission_count=mission_count)
        if down_load_res == True:
            save_path = common_DownloadPath(file_name=save_name)
            ffmpeg_mission(save_path=save_path, path=path)
        else:
            print('下载文件失败')
    else:
        print('解析 M3U8 文件失败')
